package com.jwyming.secKilling;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * Created by user on 2017/4/3.
 */
public class ConfigItem {
    Logger logger = Logger.getLogger(this.getClass().getName());
//    private static ConfigItem configInfo;
    private Properties props;

    public ConfigItem(String fileName) {
        // 载入配置文件
        props = new Properties();
        InputStream in = ConfigItem.class.getResourceAsStream(fileName);
        try {
            props.load(in);
            in.close();
        } catch(IOException ioe) {
            logger.error("载入配置文件失败: " + fileName);
            ioe.printStackTrace();
        }
    }

    public ConfigItem(InputStream inputStream) {
        props = new Properties();
        try {
            props.load(inputStream);
//            inputStream.close();
        } catch(IOException ioe) {
            logger.error("载入inputStream失败");
            ioe.printStackTrace();
        }
    }

//    public static ConfigItem getInstance() {
//        if(configInfo == null) {
//            configInfo = new ConfigItem();
//        }
//        return configInfo;
//    }

    public String getProperty(String name) {
        return props.getProperty(name);
    }

    public HashMap<String, Object> getParams(String name) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        String value = props.getProperty(name);
        String[] pairs = value.split(";");
        for(int i = 0; i < pairs.length; i++) {
            String[] keyValue = pairs[i].split(":");
            String paramName = keyValue[0];
            String paramValue = keyValue[1];
            if(paramValue.startsWith("[") && paramValue.endsWith("]")) {
                List<String> valueList = new ArrayList<String>();
                paramValue = paramValue.substring(1, paramValue.length() - 1);
//                logger.info("paramValue=" + paramValue);
                String[] values = paramValue.split(",");
                for(String tmp : values) {
                    valueList.add(tmp);
                }
                params.put(paramName, valueList);
            } else {
                params.put(paramName, paramValue);
            }
        }
        return params;
    }
}
